<template>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style="width:100%;height:100%">


        <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="20%" >
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用户信息" name="first">
              <div class="tfscrollbarstyle" style="height:300px;width:100%;">
                 <div style="width:90%">

                   <el-form-item label="用户名" prop="userName">
                     <el-input v-model="temp.userName" :disabled="dialogStatus==='update'" size="mini"></el-input>
                   </el-form-item>
                   <div style="margin-left: 20%">
                     <span>用户名填写规则：</span><br/>
                     <span>1)由汉字、英文字母（不区分大小写）、数字、点或下划线组成,长度为8-16个字符</span><br/>
                   </div>
                   <el-form-item label="真实姓名" prop="trueName">
                     <el-input v-model="temp.trueName" size="mini"></el-input>
                   </el-form-item>
                   <el-form-item v-if="dialogStatus=='create'" label="密码" prop="password">
                     <el-input v-model="temp.password" type="password" size="mini"></el-input>
                   </el-form-item>
                   <el-form-item v-if="dialogStatus=='create'" label="确认密码" prop="checkPassword">
                     <el-input v-model="temp.checkPassword" type="password" size="mini"></el-input>
                   </el-form-item>
                   <el-form-item label="手机号码" prop="mobile">
                     <el-input v-model="temp.mobile" size="mini"></el-input>
                   </el-form-item>
                   <el-form-item label="详细地址" prop="detailAddress">
                     <el-input v-model="temp.detailAddress" size="mini"></el-input>
                   </el-form-item>
                   <el-form-item label="QQ：" prop="qq">
                     <el-input v-model="temp.qq" size="mini"></el-input>
                   </el-form-item>
                   <el-form-item label="电子邮箱：" prop="email">
                     <el-input v-model="temp.email" size="mini"></el-input>
                   </el-form-item>
                   <el-form-item label="微信账号：" prop="wechat">
                     <el-input v-model="temp.wechat" size="mini"></el-input>
                   </el-form-item>
                 </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="所属组织" name="second">
              <div style="height:310px">
                <div style=" float: left;height:300px" >
                  <yfu-panel :panelParam="panelParam" >
                    <yfu-tree :param="param" v-on:nodeClick="nodeClick"  ref="yfuTreeDiv"> </yfu-tree>
                  </yfu-panel>
                </div>
                <div style=" float: left; margin-left: 20px; vertical-align: middle;width:20px;margin-top:160px;">
                  <el-button size="mini" type="success" plain @click="organizationToRight"><i class="el-icon-arrow-right" ></i></el-button><br/>
                  <el-button size="mini" type="danger" plain @click="organizationToLeft"><i class="el-icon-arrow-left" ></i></el-button>
                </div>
                <div style=" float: left; margin-left: 40px;height:300px;width:40%">

                  <!--<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox><br/>-->
                  <yfu-panel :panelParam="panelParamright" >
                    <el-checkbox-group v-model="checkedOrganizationRights">
                      <div v-for="organizationRight in organizationRights" :key="organizationRight.id">
                        <el-checkbox  :label="organizationRight.id" >{{organizationRight.label}}</el-checkbox>
                      </div>
                    </el-checkbox-group>
                  </yfu-panel>
                </div>
              </div>

            </el-tab-pane>

            <el-tab-pane label="角色设置" name="third">
              <el-transfer
                filterable
                :titles="titles"
                filter-placeholder="输入关键字"
                v-model="value3"
                :data="data3">
              </el-transfer>
            </el-tab-pane>
          </el-tabs>
        </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="updateData" size="mini">确 定</el-button>
        <el-button v-else type="primary" @click="updateData" size="mini">确 定</el-button>
      </div>
    </el-dialog>
</template>

<script type="text/javascript">
  import ElButton from '../../../node_modules/element-ui/packages/button/src/button.vue'
  import { organizationTreeApi1 } from '@/view/api/organization.js'
  import { addUser, getUserInfoByUserId, getRoleListWithoutPage, updateUserInfo, getUserByUsernameRemote, getUserByTrueNameRemote } from '@/view/api/userManager.js'
  import { yfuSuccessToast } from '@/utils/yfuMessage.js'
  import { encrypt, encryptParameter } from '@/utils/des.js'
  import {yfuPost} from '@/utils/request.js'
  export default {
    components: {
      ElButton
    },
    data () {
      return {
        activeName: 'first',
        trueNameBak: '',
        temp: {
          id: '',
          userName: '',
          trueName: '',
          password: '',
          checkPassword: '',
          mobile: '',
          detailAddress: '',
          qq: '',
          email: '',
          wechat: '',
          orgnazation: '',
          role: ''
        },
        textMap: {
          update: '修改用户',
          create: '新建用户'
        },
        dialogStatus: 'update',
        dialogFormVisible: false,
        dialogPvVisible: false,
        rules: {
          userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' },
            {min: 3, max: 16, message: '必须3-16个字符', trigger: 'blur'},
            { trigger: 'blur', validator: this.validateUsername }],
          trueName: [{max: 50, message: '最大50个字符', trigger: 'blur'}, { required: true, message: '姓名不能为空', trigger: 'blur' },
            { trigger: 'blur', validator: this.isvalidateTrueName }],
          password: [{ required: true, message: '密码不能为空', trigger: 'blur' }, {min: 3, max: 16, message: '必须3-16个字符', trigger: 'blur'}],
          checkPassword: [{required: true, message: '请再次输入密码', trigger: 'blur'}, {min: 3, max: 16, message: '必须3-16个字符', trigger: 'blur'}, { trigger: 'blur', validator: this.validatePass2 }],
          mobile: this.filter_rules({required: true, max: 11, type: 'mobile'}),
          qq: this.filter_rules({maxLength: 11, type: 'qq'}),
          email: this.filter_rules({maxLength: 50, type: 'email'}),
          wechat: [{max: 11, message: '最大11个字符', trigger: 'blur'}],
          address: [{max: 50, message: '最大50个字符', trigger: 'blur'}]
        },
        param: {
          showSearch: true,
          baseURL: process.env.BASE_API,
          url: organizationTreeApi1.url,
          urlParam: {
            id: 0
          },
          showCheckBox: true,
          highLightCurrent: false,
          width: '100%',
          height: '265px',
          checkstrictly: true
        },
        organizationchecked: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        /* el-transfer begin */
        data3: [],
        value3: [],
        titles: ['角色列表', '已选列表'],
        /* el-transfer end */
        checkAll: false,
        checkedOrganizationRights: [],
        organizationRights: [],
        panelParam: {
          title: '组织列表',
          width: '100%',
          height: '100%',
          isShowButton: false
        },
        panelParamright: {
          title: '所选组织',
          width: '100%',
          height: '100%',
          isShowButton: false
        }
      }
    },
    methods: {
      isvalidateTrueName (rule, value, callback) {
        let regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im
        let regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im
        if (value != null && value !== '') {
          if (regEn.test(value) || regCn.test(value)) {
            callback(new Error('您输入的名称包含特殊符号!'))
          } else {
            if (this.trueNameBak !== value) {
              let param = {}
              param.trueName = value
              yfuPost(process.env.BASE_API, getUserByTrueNameRemote.url, param, (data) => {
                if (data === '姓名可以注册') {
                  callback()
                } else {
                  callback(new Error('姓名已存在'))
                }
              })
            } else {
              callback()
            }
          }
        } else {
          callback()
        }
      },
      validatePass2 (rule, value, callback) {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.temp.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      validateUsername (rule, value, callback) {
        if (this.dialogStatus === 'update') {
          callback()
        }
        if (value === '') {
          callback(new Error('请输入用户名'))
        } else {
          let myreg = /^[a-zA-Z]{1}([a-zA-Z0-9]|[_]){3,16}$/
          if (!myreg.test(value)) {
            callback(new Error('您输入的用户名格式不正确!'))
          } else {
            let param = {}
            param.userName = value
            yfuPost(process.env.BASE_API, getUserByUsernameRemote.url, param, (data) => {
              if (data === '用户可以注册') {
                callback()
              } else {
                callback(new Error('用户名已存在'))
              }
            })
          }
        }
      },
      handleClick () {

      },
      createUserDialog () {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.activeName = 'first'
        this.resertDialog()
        this.param.urlParam.id = 0
        this.refreshTree()

//        this.$nextTick(() => {
//          this.$refs['dataForm'].clearValidate()
//        })

        this.getRoleList()
      },
      modifyUserDialog (data) {
        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        this.temp = data
        this.trueNameBak = data.trueName
        this.activeName = 'first'
        this.param.urlParam.id = data.id
        this.refreshTree()
        this.refreshRole()
      },
      resertDialog () {
        this.temp.userName = ''
        this.temp.trueName = ''
        this.temp.password = ''
        this.temp.checkPassword = ''
        this.temp.mobile = ''
        this.temp.detailAddress = ''
        this.temp.qq = ''
        this.temp.email = ''
        this.temp.wechat = ''
        this.temp.orgnazation = ''
        this.temp.role = ''
        this.organizationRights = []
      },
      refreshRole () {
        let cThis = this

        let params = {}
        params.id = this.temp.id
        getUserInfoByUserId(params,
          function (data) {
            console.log(data)
            let roleDataList = []
            let roleDataSelected = []
            let orgDataSelected = []

            data.roleids.forEach((role, index) => {
              roleDataList.push({
                label: role.roleName,
                key: role.id
              })
            })

            data.checkedRoleids.forEach((role, index) => {
              roleDataList.push({
                label: role.roleName,
                key: role.id
              })
              roleDataSelected.push(role.id)
            })

            data.groupids.forEach((org, index) => {
              orgDataSelected.push({
                id: org.id,
                label: org.organizationName
              })
            })

            cThis.data3 = roleDataList
            cThis.value3 = roleDataSelected
            cThis.organizationRights = orgDataSelected
          },
          function (error) {
            console.log(error)
          }
        )
      },
      getRoleList () {
        let cThis = this

        let params = {}

        getRoleListWithoutPage(params,
          function (data) {
            console.log(data)
            let roleDataList = []
            let roleDataSelected = []

            data.forEach((role, index) => {
              roleDataList.push({
                label: role.roleName,
                key: role.id
              })
            })

            cThis.data3 = roleDataList
            cThis.value3 = roleDataSelected
          },
          function (error) {
            console.log(error)
          }
        )
      },
      updateData () {
        let cThis = this

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            cThis.submitUserInfo()
          } else {
            return false
          }
        })
      },
      submitUserInfo () {
        let cThis = this

        if (this.dialogStatus === 'create') {
          let params = {}
          params.id = cThis.temp.id
          params.userName = cThis.temp.userName
          params.trueName = cThis.temp.trueName
          params.passWord = encrypt(encryptParameter.key, encryptParameter.iv, cThis.temp.password)
          params.mobile = cThis.temp.mobile
          params.detailAddress = cThis.temp.detailAddress
          params.qq = cThis.temp.qq
          params.email = cThis.temp.email
          params.wechat = cThis.temp.wechat
          if (cThis.$refs.yfuTreeDiv != null) {
            let selectedOrg = []
            cThis.organizationRights.forEach(org => {
              selectedOrg.push(org.id)
            })
            params.groupids = selectedOrg.join()
          } else {
            params.groupids = ''
          }
          params.roleids = cThis.value3.join()

          addUser(params,
            function (data) {
              console.log(data)
              cThis.dialogFormVisible = false
              cThis.$emit('listenToChildRefreshEvent')
              yfuSuccessToast('新增用户成功！')
            },
            function (error) {
              console.log(error)
            }
          )
        } else {
          let params = {}
          params.id = cThis.temp.id
          params.userName = cThis.temp.userName
          params.trueName = cThis.temp.trueName
          params.mobile = cThis.temp.mobile
          params.detailAddress = cThis.temp.detailAddress
          params.qq = cThis.temp.qq
          params.email = cThis.temp.email
          params.wechat = cThis.temp.wechat
          if (cThis.$refs.yfuTreeDiv != null) {
            let selectedOrg = []
            cThis.organizationRights.forEach(org => {
              selectedOrg.push(org.id)
            })
            params.groupids = selectedOrg.join()
          } else {
            params.groupids = ''
          }
          params.roleids = cThis.value3.join()
          params.modifyUserInfoType = 0

          updateUserInfo(params,
            function (data) {
              console.log(data)
              cThis.dialogFormVisible = false
              cThis.$emit('listenToChildRefreshEvent')
              yfuSuccessToast('修改成功！')
            },
            function (error) {
              console.log(error)
            }
          )
        }
      },
      filterNode (value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      nodeClick (data) {
        console.log(data)
      },
      getAllCheckeds () {
        this.organizationchecked = this.$refs.yfuTreeDiv.getAllCheckeds()
        console.log(this.organizationchecked)
        this.organizationRights = this.organizationchecked
      },
      refreshTree () {
        if (this.$refs.yfuTreeDiv != null) {
          this.$refs.yfuTreeDiv.refresh()
        }
      },
      organizationToRight () {
        this.getAllCheckeds()
      },
      organizationToLeft () {
        for (let id of this.checkedOrganizationRights) {
          for (var i = 0; i < this.organizationRights.length; i++) {
            if (this.organizationRights[i].id === id) {
              this.organizationRights.splice(i, 1)
              break
            }
          }
        }
        let arrayCheck = []
        for (let c of this.organizationRights) {
          arrayCheck.push(c.id)
        }
        this.$refs.yfuTreeDiv.setKeys(arrayCheck)
      }
    },
    watch: {
      filterText (val) {
        this.$refs.tree2.filter(val)
      }
    }
  }
</script>

<style>

</style>
